package controllers

import (
	"github.com/kataras/iris"
	"log"
	"lottery/comm"
	"lottery/models"
	"lottery/services"
	"lottery/web/utils"
)

type PlayController struct {
	Ctx           iris.Context
	ServiceUser   services.UserService
	ServiceAward  services.AwardService
	ServiceEvent  services.EventService
	ServiceResult services.ResultService
}

// POST /play/roll params: token
// 刮刮乐摇奖
func (c *PlayController) PostRoll() map[string]interface{} {

	token := c.Ctx.FormValue("token")
	ret, claims, err := utils.VerifyESToken(token)
	if err != nil {
		// token 解析失败
		log.Println("play.PostPlay() failed, err=", err)
		utils.RespCode(500)
	} else if !ret {
		// token 无效
		utils.RespCode(100)
	}
	userId := int(comm.GetInt64(claims.Get("user_id"), -1))
	eventId := int(comm.GetInt64(c.Ctx.FormValue("event_id"), -1))

	// 1. 先检查用户是否被锁定，若否通过 redis 将用户锁定
	ok := utils.LockLucky(userId)
	if ok {
		// 锁定成功
		defer utils.UnlockLucky(userId)
	} else {
		// 锁定失败，已经在抽奖
		return map[string]interface{}{
			"code": 220,
			"msg":  "you are already drawing lottery",
		}
	}

	// 2. 检查用户是否有资格

	// 3. 开始抽奖
	has, _ := c.ServiceEvent.Get(eventId)
	log.Println("has=", has)
	if !has {
		// 活动不存在
		return utils.RespCode(210)
	}
	awards := c.ServiceAward.GetByEvent(eventId)
	random := comm.Random(1000)

	for _, award := range awards {
		if random >= award.AreaFrom && random <= award.AreaTo {
			if award.RestAmount > 0 {

				if i, err := c.ServiceAward.DecrLeftNum(award.Id, 1); err != nil {
					return utils.RespCode(500)
				} else if i <= 0 {
					// todo 插入记录
					return map[string]interface{}{
						"code":       "0",
						"msg":        "success",
						"award":      "谢谢惠顾！",
						"pic":        "",
						"award_code": "",
					}
				}
				err := c.ServiceAward.Update(&award, []string{"rest_amount"})
				if err != nil {
					// 更新失败
					utils.RespCode(500)
				}
				award_code := utils.UUID()
				err = c.ServiceResult.Create(&models.TbResult{
					EventId:    eventId,
					AwardId:    award.Id,
					WinnerId:   userId,
					Status:     2,
					AwardCode:  award_code,
					CreateTime: comm.NowUnix(),
					UpdateTime: comm.NowUnix(),
				})
				if err != nil {
					// 插入失败
					utils.RespCode(500)
				}
				return map[string]interface{}{
					"code":       "0",
					"msg":        "success",
					"award":      award.Name,
					"pic":        award.Img,
					"award_code": award_code,
				}
			} else {
				// todo 插入记录
				return map[string]interface{}{
					"code":       "0",
					"msg":        "success",
					"award":      "谢谢惠顾！",
					"pic":        "",
					"award_code": "",
				}
			}
		}
	}
	return utils.RespCode(500)
}
